<template>
  <!-- 地图容器 -->
  <div id="mapContainer" class="map">
    <div
      class="custom-menu"
      @mouseleave="mouseleaveFn"
      v-if="showMenu"
      :style="{ top: menuPosition.y + 'px', left: menuPosition.x + 'px' }"
    >
      <div v-for="item in fenceMenuList" :key="item.fenceIndex">
        <span>围栏{{ item.fenceIndex + 1 }}</span>
        <span>
          <a class="fixed-btn" v-if="+item.type === 2" @click="emit('editFence', item)">编辑</a>
          <a class="fixed-btn" v-if="electricFenceList.length > 1" @click="emit('deleteFence', item)">删除</a>
        </span>
      </div>
    </div>
  </div>
</template>
<script setup>
  import { loadMapScript } from '@/utils/loadMap'
  import { ref, nextTick, onMounted } from 'vue'
  const map = ref(null)
  onMounted(() => {
    // 加载地图
    loadMapScript().then(() => {
      nextTick(() => {
        init()
      })
    })
  })
  defineProps({
    fenceMenuList: Array,
    electricFenceList: Array,
  })
  const emit = defineEmits(['editFence', 'deleteFence', 'refreshMap'])
  const showMenu = ref(null)
  const menuPosition = ref({ x: 0, y: 0 })
  const showCustomMenu = (lnglat, pixel) => {
    // 设置菜单的显示位置和状态
    menuPosition.value.x = pixel.getX()
    menuPosition.value.y = pixel.getY()
    showMenu.value = true
  }

  const mouseleaveFn = () => {
    showMenu.value = false
  }

  const init = async () => {
    await polyfillNewMap()
    await polyfillAddToolBar()
    await emit('refreshMap')
  }

  // 清空覆盖物
  const polyfillClearMap = () => {
    if (!map.value) return
    map.value.clearMap()
  }

  // 增加工具条
  const polyfillAddToolBar = (offset = [10, 10]) => {
    map.value.addControl(
      new AMap.ToolBar({
        position: 'RB',
        offset,
      })
    )
  }

  // 初始化地图
  const polyfillNewMap = (config = {}, containerId = 'mapContainer') => {
    const { center = [116.397428, 39.90923], zoom = 16 } = config
    map.value = new AMap.Map(containerId, {
      center,
      zoom,
      scrollWheel: false, // 禁止鼠标滚轮放大缩小地图
      touchZoom: false, // 禁止触摸板放大缩小地图
      doubleClickZoom: false, // 禁止鼠标双击放大地图
      ...config,
    })
  }

  defineExpose({
    map,
    showMenu,
    polyfillClearMap,
    showCustomMenu,
  })
</script>
<style lang="less" scoped>
  .map {
    min-width: 600px;
    height: 600px;
    position: relative;
  }
  .custom-menu {
    position: absolute;
    background-color: #fff;
    border: 1px solid #ccc;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
    padding: 8px;
    z-index: 100;

    cursor: pointer;
  }

  .custom-menu div {
    padding: 6px 12px;
    width: 200px;
    display: flex;
    justify-content: space-between;
    color: #333;
  }

  .custom-menu div:hover {
    background-color: #f0f0f0;
  }
  .fixed-btn {
    margin-right: 5px;
    &:hover {
      color: #165dffff;
    }
  }
</style>
